#include "HiRtpCommonUtil.h"
#include "ParserPacket.hpp"
#include "RTPDecoderWrapper.hpp"
#include "RTPSharePicture.hpp"
#include "RtpPacket.hpp"
#include "UdpSocketWrapper.hpp"
#include "hiScopeGuard.h"
#include <arpa/inet.h>
#include <gtest/gtest.h>

static const char *myIp = "127.0.0.1";

using namespace Hi;
using namespace std;
static Hi::RTPDecoderWrapper decoder;

static uint16_t seq = 0;

static const char *url = "/tmp/hi/video_test_111";
static void UdpReceiveMsg(const uint8_t *data, size_t len,
                          const struct sockaddr *addr,
                          UdpSocketWrapper *wrapper) {
    RtpPacket *packet = hi_RtpPacket_parse(data, len);
    if (packet == nullptr) {
        return;
    }

    if (seq + 1 != packet->GetSequenceNumber()) {
        printf("packet seq:%d, last seq:%d\n", packet->GetSequenceNumber(),
               seq);
    }
    seq = packet->GetSequenceNumber();
    decoder.Decode(packet);
    hi_RtpPacket_release(&packet);
}

TEST(RTPPicShare, createShareMemeory_folder_not_exist) {
    Hi::RTPSharePicture handle;
    bool isSuccess = handle.Start("/tmp/hi1212/video_test_122", 1920, 1080);
    EXPECT_EQ(isSuccess, false);
}

TEST(RTPPicShare, createShareMemeory_folder_exist) {
    system("mkdir /tmp/hi");
    Hi::RTPSharePicture handle;
    bool isSuccess = handle.Start(url, 1920, 1080);
    EXPECT_EQ(isSuccess, true);
}

static uint32_t s_index = 0;
static void OnRGB(const uint8_t *data, uint32_t width, uint32_t height);
static void OnYUV(const uint8_t *data, uint32_t width, uint32_t height);
TEST(RTPPicShare, decoderRTSP) {
    // return;
    // system("rm -fr bmp/*");
    system("mkdir /tmp/hi");
    Hi::RTPSharePicture handle;
    decoder.Start(handle, 1920, 1080, nullptr);
    handle.SetCallback(OnRGB, OnYUV);
    bool isSuccess = handle.Start(url, 1920, 1080);
    EXPECT_EQ(isSuccess, true);
    ON_SCOPE_EXIT([&]() { handle.Stop(); });
    UdpSocketWrapper *udp = new UdpSocketWrapper();
    int ret = udp->Listen(myIp, 60001, UdpReceiveMsg);
    EXPECT_EQ(ret, 0);
    sleep(1000000);
}

static void OnRGB(const uint8_t *data, uint32_t width, uint32_t height) {
    return;
    stringstream oss;
    oss << "./bmp/" << s_index % 100 << "_cpp.bmp";
    hi_saveBmp(oss.str().c_str(), data, width, height);
    s_index++;
}

static void OnYUV(const uint8_t *data, uint32_t width, uint32_t height) {
    printf("OnYUV\n");
}